package service

import (
	"ruoyi-go-echo-ddd/internal/domain/model"
	"ruoyi-go-echo-ddd/internal/domain/repository"
	"ruoyi-go-echo-ddd/internal/infrastructure/utils"

	"github.com/labstack/echo/v4"
)

type PermissionService struct {
	roleRepo repository.SysRoleRepository
	menuRepo repository.SysMenuRepository
}


func NewPermissionService(roleRepo repository.SysRoleRepository, menuRepo repository.SysMenuRepository) *PermissionService{
	return &PermissionService{
		roleRepo: roleRepo,
		menuRepo: menuRepo,
	}
}

func (s *PermissionService) SelectRolePermission(e echo.Context, userId int64) ([]string, error) {
	var permissions []string
	isAdmin := model.IsAdmin(userId)
	if isAdmin {
		permissions = append(permissions, "admin")
	} else {
		permissionList, err := s.roleRepo.SelectRolePermsByUserId(e.Request().Context(), userId)
		if err != nil {
			return nil, err
		}
		permissions = permissionList
	}
	return permissions, nil
}

func (s *PermissionService) SelectMenuPermission(e echo.Context, userId int64) ([]string, error) {
	var permissions []string
	isAdmin := model.IsAdmin(userId)
	if isAdmin {
		permissions = append(permissions, "*:*:*")
	} else {
		permissionList, err := s.menuRepo.SelectMenuPermsByUserId(e.Request().Context(), userId)
		if err != nil {
			return nil, err
		}
		permissions = utils.DeduplicateStrings(permissionList)
	}
	return permissions, nil
}